package cn.edu.ncut.cs.springboot.petmanagementsystem.Util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;
import java.util.Map;

public class JwtUtil {

    // 建议改成配置文件读取
    private static final String SECRET_KEY = "your-256-bit-secret-your-256-bit-secret"; // 长度至少32字节
    private static final long EXPIRATION_TIME = 1000 * 60 * 60 * 2; // 2小时

    private static Key getSigningKey() {
        return Keys.hmacShaKeyFor(SECRET_KEY.getBytes(StandardCharsets.UTF_8));
    }

    /** 生成JWT */
    public static String generateToken(String username, Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(getSigningKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    /** 验证并解析JWT */
    public static Jws<Claims> parseToken(String token) throws JwtException {
        return Jwts.parserBuilder()
                .setSigningKey(getSigningKey())
                .build()
                .parseClaimsJws(token);
    }

    /** 获取用户名 */
    public static String getUsername(String token) {
        try {
            return parseToken(token).getBody().getSubject();
        } catch (Exception e) {
            return null;
        }
    }

    /** 判断是否过期 */
    public static boolean isTokenExpired(String token) {
        try {
            Date expiration = parseToken(token).getBody().getExpiration();
            return expiration.before(new Date());
        } catch (Exception e) {
            return true;
        }
    }

    /** 获取用户ID */
    public static Long getUserId(String token) {
        try {
            Object userId = parseToken(token).getBody().get("userId");
            if (userId instanceof Integer) {
                return ((Integer) userId).longValue();
            }
            return (Long) userId;
        } catch (Exception e) {
            return null;
        }
    }
}
